#include "SyncTime.h"

//SyncTime::instance(4000)->Start();
SyncTime *SyncTime::instance(int port){
	static SyncTime sm_instance(port);
	return &sm_instance;
}

SyncTime::SyncTime(int port) : _port(port){
    _socket = Socket::createSocket(EventPollerPool::Instance().getPoller());
    _socket->setOnRead([this](const Buffer::Ptr &buf, struct sockaddr *addr, int addr_len) {
    	OnUdpData(buf, addr, addr_len);
    });
}

bool SyncTime::Start(){
	if (!_socket->bindUdpSock(_port, "::")){
		errorf("bind error");

		return false;
	}

	return true;
}

bool SyncTime::OnUdpData(const Buffer::Ptr &buf, struct sockaddr *peer_addr, int interleaved){

	//!!! Parse
	int i = 0;
	uint64_t time = 0;
	
	uint64_t base = 1;
	char timebuf[100] = {0};
	char localtimebuf[100] = {0};
	
	strncpy(timebuf, buf->data(), buf->size());
	printf("%s\n",timebuf);
	uint64_t localtime1 = getCurrentMillisecond();
	//printf("localtime1 = %llu\n",localtime1);
	for(i = 0; i < buf->size(); i++)
	{
		time = time + (uint64_t)(timebuf[buf->size()-1-i] - '0') * base;
		base = base * 10;
	}
	
	//printf("time = %llu\n",time);
	
	setSystemTimeMs(time);
	system("hwclock -w");
	uint64_t localtime2 = getCurrentMillisecond();
	//printf("localtime1 = %llu, localtime2 = %llu\n",localtime1, localtime2);
	uint64_t localtime = getCurrentMillisecond(1);
	sprintf(localtimebuf, "%llu", localtime);
	
	_socket->send(localtimebuf, peer_addr, interleaved, true);
	return true;
}
